package tech.yangzhijie.basic.demo02.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Tests {
    private static final Logger logger = LoggerFactory.getLogger(Tests.class);
    //读取公私钥⽂文件
    public static String readKeyFile(String keyFile) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(keyFile)));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) != '-') {
                sb.append(readLine);
                sb.append(System.getProperty("line.separator"));
            }
        }
        return sb.toString();
    }
    public static String readKeyStr(String keyStr) throws Exception {
        String[] lines = keyStr.trim().split("\n");
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            String readLine = line.trim();
            if (readLine.charAt(0) != '-') {
                sb.append(readLine);
                sb.append(System.getProperty("line.separator"));
            }
        }
        return sb.toString();
    }
    //构造私钥对象
    public static PrivateKey loadPrivateKey(String privateKey) throws Exception {
// 解密由base64编码的私钥
        byte[] keyBytes = Base64.decodeBase64(privateKey);
// 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 取私钥匙对象
        return keyFactory.generatePrivate(pkcs8KeySpec);
    }
    //构造公钥对象
    public static PublicKey loadPublicKey(String publicKey) throws Exception {
        byte[] buffer = Base64.decodeBase64(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
        return keyFactory.generatePublic(keySpec);
    }
    //rsa加密
    public static byte[] rsaEncrypt(RSAPublicKey publicKey, byte[]
            plainTextData)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(plainTextData);
    }
    //rsa解密
    public static byte[] rsaDecrypt(RSAPrivateKey privateKey, byte[]
            cipherData)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(cipherData);
    }
    public static String rsaSign(PrivateKey privateKey, String plainText)
            throws Exception {
        Signature sig = Signature.getInstance("SHA1WithRSA");
        sig.initSign(privateKey);
        byte[] plainTextData = plainText.getBytes("UTF-8");
        sig.update(plainTextData);
        byte[] signature = sig.sign();
        return Base64.encodeBase64String(signature);
    }

    public static void main(String[] args) throws Exception{
        String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOR4wcbH3DSFn8odaX12rO25k/mMGrvPBoRKAc2Nlc2JcGm/xJpl44SrlS81M0tbGLEFV+2I/1w49+EG5+zDI72j6whGdZh//E7XZImJtDBHiH9hKwzLmGs+2g7Y2juJxvZZiRQHVfpWL62Tqf1mA3xaFfZEiP/EHujKuUjsizG5AgMBAAECgYBWd4lG1O73Bbdiw9zfueFamwhwwmB/watCt8uU4sfWIPTlYMlkcbk4xcNROX4vP8vJey8628VhPsI5bOariXLlpKYqPMpVqw1oWCnEG0+YdPw1oszYG8wKNWsJgkCncGGE9jOMbAQKw7AkUbPSfmOflkMfr7HyuuB6bzmD1OFUgQJBAPWgOlWuFsb3NRbwLkf7EGLp3MNtlrCtjjet8B57kX7ry+PTSDQz3J0ochREUSiBi6bKoQPbCyR7eRG/MdlhcAkCQQDuHw2yJMFW5OzGnX6YnxtdxmBSeNNPe4Goqu29bvxFqDyjeDu7raxQk8xucBB6logS/yQ3xqZuVM4nztKRbsAxAkEAhbDzb2U1IpC1Rcnu9uDRV3VA4uIILhwZF3dGBeFuHO4M6PE8EKXVw3ibNyrEHc79CwipQSb9VpsaF63AXThquQJBANl/ic3+3o4VGeSstJaJNcDo0tBhxnliEWNThUWzWz/w1DpoNv9NOgh7h44UVCj02COp4pYDn79FPOyFcDYgl/ECQQDnxQO/pIzhKgOhqSsRDUx0HHTvjMbjPnrrtooDLHFbohNkCEFrW04mpyzA5CQsJS/R6WPu4frQanCEIwLR7fST";
        String t = "app_id=273516754758160&id_type=imei&id_value=355637052788650&req_id=280697745622712320";//imei示例例，注意key需要按字典序拼接
        String s1 = rsaSign(loadPrivateKey(privateKey), t);
        System.out.println(s1);
        String signstr=URLEncoder.encode(s1, "UTF-8");//最终的sign结果,z注意必须要做URLEncoder！

        System.out.println(signstr);
        String final_url="https://open.umeng.com/cplus/credit?"+t+"&sign="+signstr;
        System.out.println(final_url);
        String result = HttpClientUtil.sendGet(final_url);
        System.out.println(result);
        //最终url示例例：plainText)
        //https://open.umeng.com/cplus/credit?app_id=ur_app_id&id_type=imei&id_value=860529038487085&req_id=2017022813&sign=以上signstr！！！
    }

    public static boolean rsaSignCheck(PublicKey publicKey, String
            plainText, String sign) {
        try {
//sign = URLDecoder.decode(sign, "UTF-8");
            Signature sig = Signature.getInstance("SHA1WithRSA");
            sig.initVerify(publicKey);
            byte[] plainTextData = plainText.getBytes("UTF-8");
            sig.update(plainTextData);
            byte[] signature = Base64.decodeBase64(sign);
            return sig.verify(signature);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("rsaSignCheck: param={}, sign={}", plainText,
                    sign);
        }
        return false;
    }

    @Test
    public void name() throws Exception {
        String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOR4wcbH3DSFn8odaX12rO25k/mMGrvPBoRKAc2Nlc2JcGm/xJpl44SrlS81M0tbGLEFV+2I/1w49+EG5+zDI72j6whGdZh//E7XZImJtDBHiH9hKwzLmGs+2g7Y2juJxvZZiRQHVfpWL62Tqf1mA3xaFfZEiP/EHujKuUjsizG5AgMBAAECgYBWd4lG1O73Bbdiw9zfueFamwhwwmB/watCt8uU4sfWIPTlYMlkcbk4xcNROX4vP8vJey8628VhPsI5bOariXLlpKYqPMpVqw1oWCnEG0+YdPw1oszYG8wKNWsJgkCncGGE9jOMbAQKw7AkUbPSfmOflkMfr7HyuuB6bzmD1OFUgQJBAPWgOlWuFsb3NRbwLkf7EGLp3MNtlrCtjjet8B57kX7ry+PTSDQz3J0ochREUSiBi6bKoQPbCyR7eRG/MdlhcAkCQQDuHw2yJMFW5OzGnX6YnxtdxmBSeNNPe4Goqu29bvxFqDyjeDu7raxQk8xucBB6logS/yQ3xqZuVM4nztKRbsAxAkEAhbDzb2U1IpC1Rcnu9uDRV3VA4uIILhwZF3dGBeFuHO4M6PE8EKXVw3ibNyrEHc79CwipQSb9VpsaF63AXThquQJBANl/ic3+3o4VGeSstJaJNcDo0tBhxnliEWNThUWzWz/w1DpoNv9NOgh7h44UVCj02COp4pYDn79FPOyFcDYgl/ECQQDnxQO/pIzhKgOhqSsRDUx0HHTvjMbjPnrrtooDLHFbohNkCEFrW04mpyzA5CQsJS/R6WPu4frQanCEIwLR7fST";
        String t = "app_id=273516893448720&id_type=imei&id_value=355637052238805&req_id=741852963963852741";//imei示例例，注意key需要按字典序拼接
        String s1 = rsaSign(loadPrivateKey(privateKey), t);
        System.out.println(s1);
        String signstr=URLEncoder.encode(s1, "UTF-8");//最终的sign结果,z注意必须要做URLEncoder！

        System.out.println(signstr);
        String final_url="https://open.umeng.com/cplus/credit?"+t+"&sign="+signstr;
        String result = HttpClientUtil.sendGet(final_url);
        System.out.println(result);
    }

    @Test
    public void 测试并发() {
        List<Integer> list = new ArrayList<>(10000);
        for (int i = 0; i < 10000; i++) {
            list.add(i);

        }

    }

    private void sleep() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
    }

    @Test
    public void name12() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "李小苛");
        jsonObject.put("idCard", "410825198305204017");
        jsonObject.put("mobile", "17703912356");
        System.out.println(jsonObject.toJSONString());

        StringBuilder url = new StringBuilder("?");
        jsonObject.entrySet().stream().forEach(e->{
            if(url.toString().endsWith("?")){
                url.append(e.getKey()+"="+e.getValue());
            }else {
                url.append("&"+e.getKey()+"="+e.getValue());
            }
        });
        System.out.println(url);
    }
}
